import { findDetectionTemplate } from '@/api/standardizedDetection/detectionTemplate';
import { Button, Col, Form, Input, message, Modal, Row, Select } from 'antd';
import { formatDate } from '@/utils';
import { useEffect, useMemo, useState } from 'react';
import TemplateConfiguration from '@/components/ArchivesDetection/conponentes/DetectionTemplate';
import { useArchivesDetectionContext } from '../contexts/ArchivesDetectionContext';
const { Option } = Select;
const { TextArea } = Input;

const type = [
  { id: 1, value: '条目与原文' },
  { id: 2, value: '条目' },
  { id: 3, value: '原文' },
  { id: 4, value: 'EEP格式包' },
  { id: 5, value: '光盘格式' },
  { id: 6, value: '系统环境' }
];
interface IInspectionTasksProps {
  visible: boolean;
  onClose: any;
  data: any;
  addStandardizedList?: any;
  editStandardizedList?: any;
  archiveType: any;
}
const warning = () => {
  message.warning('请选择检测类型');
};
const DetectionTask = (props: IInspectionTasksProps) => {
  const [form] = Form.useForm();

  const [moduleChange, setModuleChange] = useState('');
  const [templateVisible, setTemplateVisible] = useState(false);
  // 传入档案类型和检测类型
  const [archiveTypeId, setArchiveTypeId] = useState<number>();
  const [detectionType, setDetectionType] = useState<string>();
  const [archiveAndDetection, setArchiveAndDetection] = useState({});

  const [disabled, setDisabled] = useState(false);
  /* 传入模板数据 */
  const [configurationData, setConfigurationData] = useState<any>({});
  const { visible, onClose, data, addStandardizedList, editStandardizedList, archiveType } = props;
  const {
    DetectionTemplate,
    searchTemplateTaskList,
    archiveTypeList,
    setArchiveType,
    clearDetectionTemplate,
    DetectionTemplateId
  } = useArchivesDetectionContext();

  /* 初始传参 */
  useEffect(() => {
    clearDetectionTemplate();
    setArchiveType(archiveType);
    if (visible) {
      if (data.archiveTypeId) {
        if (data.attOriginal.status || data.attItemsList.some((item: any) => item.status)) {
          setDisabled(true);
        }
        searchTemplateTaskList({ archiveTypeId: data.archiveTypeId });
        setArchiveTypeId(data.archiveTypeId);
        setDetectionType(data.detectionType);
        form.setFieldsValue({ ...data });

        findDetectionTemplate(data.templateId).then((res: any) => {
          const { data } = res;
          if (!data) {
            form.setFieldsValue({ templateId: null });
            handleChange(0);
            message.success('当前模板已被删除');
          } else {
            setModuleChange(data.templateDesc);
            setConfigurationData(data);
          }
        });
      } else {
        searchTemplateTaskList({ archiveTypeId: data });
        setArchiveTypeId(data);
        form.resetFields();
        form.setFieldsValue({ archiveTypeId: data, name: formatDate(new Date().getTime()) });
      }
    } else {
      setModuleChange('');
      setDetectionType('');
    }
  }, [visible]);

  useEffect(() => {
    console.log(DetectionTemplate.filter((item: any) => item.detectionType === detectionType));
    console.log(DetectionTemplateId);
    if (DetectionTemplateId) {
      // setDetectionType(DetectionTemplateId);
      form.setFieldsValue({ templateId: DetectionTemplateId });
    }
    console.log(form.getFieldValue('templateId'));
    if (form.getFieldValue('templateId')) {
      findDetectionTemplate(form.getFieldValue('templateId')).then((res: any) => {
        const { data } = res;
        if (!data) {
          form.setFieldsValue({ templateId: null });
          handleChange(0);
          message.success('当前模板已被删除');
        } else {
          setModuleChange(data.templateDesc);
          setConfigurationData(data);
        }
      });
    }
  }, [detectionType, DetectionTemplate]);

  /* 选择模板并查找当前档案类型所有的模板 */
  const handleChange = (value: number) => {
    if (value) {
      findDetectionTemplate(value).then((res: any) => {
        const { data } = res;
        console.log('data', data);
        if (!data) {
          message.success('当前模板已被删除');
        } else {
          setModuleChange(data.templateDesc);
          setConfigurationData(data);
        }
      });
    } else {
      setConfigurationData('');
    }
  };
  /* 点击模板设计触发 */
  const template = () => {
    if (detectionType) {
      setArchiveAndDetection({ archiveTypeId, detectionType });
      console.log(archiveAndDetection);
      setTemplateVisible(true);
    } else {
      message.warning('请先选择检测类型');
    }
  };

  const onChangeType = (event: string) => {
    handleChange(0);
    form.setFieldsValue({ templateId: null });
    setDetectionType(event);
  };

  /**
   * @description 提交表单,触发onFinish方法
   */
  const submitFunc = () => {
    form.submit();
  };

  const onFinish = (values: any) => {
    if (data.templateId) {
      const param = {
        ...data,
        detectionType,
        name: values.name,
        templateId: values.templateId
      };

      editStandardizedList({ ...data, ...param });
    } else {
      const param = {
        archiveTypeId,
        detectionType,
        name: values.name,
        templateId: values.templateId
      };
      // if(data)
      addStandardizedList({ ...param });
    }
    form.setFieldsValue({});
    onClose();
  };

  return (
    <>
      <Modal
        visible={visible}
        title={'规范性检测任务'}
        destroyOnClose
        onCancel={onClose}
        footer={[
          <Button key="back" onClick={onClose}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => submitFunc()}>
            保存
          </Button>
        ]}
      >
        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{}}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Form.Item label="档案类型" name="archiveTypeId" rules={[{ required: true }]}>
            <Select placeholder="=请选择档案类型=" disabled>
              {archiveTypeList.map((item: any) => (
                <Option value={item.id} key={item.id}>
                  {item.atName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="检测任务名称" name="name" rules={[{ required: true }]}>
            <Input placeholder="请设置检测模板名称" />
          </Form.Item>
          <Form.Item label="检测类型" name="detectionType" rules={[{ required: true }]}>
            <Select placeholder="=请选择检测类型=" onChange={onChangeType} disabled={disabled}>
              {type.map((item: any) => (
                <Option value={item.id} key={item.id}>
                  {item.value}检测
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="检测模板"
            extra={
              <>
                <div>
                  模板说明：
                  {moduleChange === '' ? '请选择模板' : moduleChange}
                </div>
              </>
            }
            required
            style={{ marginBottom: 0 }}
          >
            <Row>
              <Col span={18}>
                <Form.Item
                  noStyle
                  name="templateId"
                  rules={[{ required: true, message: '请选择检测模板' }]}
                >
                  <Select onChange={handleChange} placeholder="=请先选择检测类型=" allowClear>
                    {DetectionTemplate.filter(
                      (item: any) => item.detectionType === detectionType
                    ).map((item: any) => (
                      <Option value={item.id} key={item.id}>
                        {item.templateName}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Button
                  type="link"
                  onClick={() => {
                    template();
                  }}
                >
                  模板设计
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item label="任务说明" name="remark">
            <TextArea rows={4} placeholder="请填写备注信息" />
          </Form.Item>
        </Form>
        {useMemo(
          () => (
            <TemplateConfiguration
              visible={templateVisible}
              onClose={() => setTemplateVisible(false)}
              ArchiveAndDetection={archiveAndDetection}
              fileData={configurationData}
              archiveTypeList={archiveTypeList}
            />
          ),
          [templateVisible]
        )}
      </Modal>
    </>
  );
};
export default DetectionTask;
